<?php

class JiangQie_API_UserPost_Controller extends JiangQie_API_Base_Controller
{
	public function __construct()
	{
		parent::__construct();
		$this->module = 'userpost';

	}

	public function register_routes()
	{

		register_rest_route($this->namespace, '/' . $this->module . '/post-add', [
			[
                'methods' => 'POST',
				'callback' => [$this, 'post_add'],
			]
		]);
        register_rest_route($this->namespace, '/' . $this->module . '/post-del', [
            [
                'methods' => 'POST',
                'callback' => [$this, 'post_del'],
            ]
        ]);
        register_rest_route($this->namespace, '/' . $this->module . '/post-list', [
            [
                'methods' => 'POST',
                'callback' => [$this, 'post_list'],
            ]
        ]);
        register_rest_route($this->namespace, '/' . $this->module . '/post-detail', [
            [
                'methods' => 'POST',
                'callback' => [$this, 'post_detail'],
            ]
        ]);
        register_rest_route($this->namespace, '/' . $this->module . '/post-publish', [
            [
                'methods' => 'POST',
                'callback' => [$this, 'post_publish'],
            ]
        ]);

	}
	public function post_add(){
        header("Access-Control-Allow-Credentials: true");
        header("Access-Control-Allow-Origin: *");
        //CORS
        header("Access-Control-Request-Methods:GET, POST, PUT, DELETE, OPTIONS");
        header('Access-Control-Allow-Headers:x-requested-with,content-type,test-token,test-sessid');//注意头部自定义参数不要用下划线


	    //  '内容类型ID（1我要晒机2配置清单3闲聊灌水）',
	    $type = isset($_POST['type']) ? $_POST['type'] : 0;
        $content = isset($_POST['content']) ? $_POST['content'] : '';
        $photos = isset($_POST['photos']) ? $_POST['photos'] : [];
        $parts = isset($_POST['parts']) ? $_POST['parts'] : [];

        if(!$type || !$content){
            return $this->make_error("内容缺失不符合要求");
        }

        //先保存到数据库

        //根据图片数量生成对应数量的md5文件名
        $photos_fileinfo = [];
        foreach($photos as $photo){
            $path = "wp-content/uploads/".date("Y/m",time());
            $name = uniqid("userphotos_")."_".uniqid(rand(),true).".jpg";
            $path_name = "wp-content/uploads/".date("Y/m",time())."/".uniqid("userphotos_")."_".uniqid(rand(),true).".jpg";
            $photos_fileinfo[] = [
                'path' => $path,
                'name' => $name,
                'path_name' => $path_name
            ];
        }

        //生成保存数据库的photos路径信息
        $photo_paths = [];
        foreach ($photos_fileinfo as $f){
            $photo_paths[] = '/'.$f['path_name'];
        }
        //先插入数据
        global $wpdb;

        //添加
        $wpdb->insert('user_post',[
            'type' => $type,
            'content' => $content,
            'photos' => implode(',',$photo_paths),
            'parts' => implode(',', $parts),
            'create_time' => date("Y-m-d H:i:s",time()),
            'update_time' => date("Y-m-d H:i:s",time())
        ]);

        //保存图片
        foreach($photos as $k=>$p){
           downloadBase64image($p,$photos_fileinfo[$k]);
        }

        return $this->make_success('发布成功');
    }

    public function post_del(){
        header("Access-Control-Allow-Credentials: true");
        header("Access-Control-Allow-Origin: *");
        //CORS
        header("Access-Control-Request-Methods:GET, POST, PUT, DELETE, OPTIONS");
        header('Access-Control-Allow-Headers:x-requested-with,content-type,test-token,test-sessid');//注意头部自定义参数不要用下划线

        $id = isset($_POST['id']) ? $_POST['id'] : 0;

        if(!$id) return $this->make_error("没有ID，删除失败");

        global $wpdb;
        $user_post = $wpdb->get_row("select * from user_post where id = {$id}");

        if($user_post){

            // 先删除文件
            if($user_post->photos){
                $photos = explode(',',$user_post->photos);
                foreach ($photos as $p){
                    if(file_exists($p)) {
                        unlink($p);
                    }
                }
            }

            // 再删除记录
            $wpdb->query("delete from user_post where id = {$id}");

            return $this->make_success('删除成功');
        }else{
            return $this->make_error('帖子不存在');
        }

    }

    public function post_list(){

        header("Access-Control-Allow-Credentials: true");
        header("Access-Control-Allow-Origin: *");
        //CORS
        header("Access-Control-Request-Methods:GET, POST, PUT, DELETE, OPTIONS");
        header('Access-Control-Allow-Headers:x-requested-with,content-type,test-token,test-sessid');


        $type = isset($_POST['type']) ? $_POST['type'] : 0;//'内容类型ID（0所有1我要晒机2配置清单3闲聊灌水）',
        $status = isset($_POST['status']) ? $_POST['status'] : 0;//审核状态（0待审核1通过）
        $page = isset($_POST['page']) ? $_POST['page'] : 0;//页面,从0开始



        $where = [];
        $where[] = '1=1';
        $type && $where[] = "type = {$type}";
        $where[] = "status = {$status}";

        $where = implode(' and ', $where);
        $limit = $page*12 . ',12';


        global $wpdb;
        $list = $wpdb->get_results("select * from user_post where {$where} limit {$limit}");



        return $this->make_success(['list'=>$list]);

    }


    public function post_detail(){
        header("Access-Control-Allow-Credentials: true");
        header("Access-Control-Allow-Origin: *");
        //CORS
        header("Access-Control-Request-Methods:GET, POST, PUT, DELETE, OPTIONS");
        header('Access-Control-Allow-Headers:x-requested-with,content-type,test-token,test-sessid');//注意头部自定义参数不要用下划线

        $id = isset($_POST['id']) ? $_POST['id'] : 0;

        if(!$id){
            return $this->make_error("没有ID，删除失败");
        }

        global $wpdb;
        $user_post = $wpdb->get_row("select * from user_post where id = {$id}");

        if($user_post){

            //处理图片
            $user_post->photos = explode(',', $user_post->photos);

            //处理零件
            $parts_arr = [];

            if($user_post->parts){
                $parts = explode(',', $user_post->parts);
                foreach ($parts as $part_id){
                    $part = $wpdb->get_row("select * from parts where id = {$part_id}");
                    if($part){
                        $parts_arr[] = $part;
                    }
                }
            }
            $user_post->parts = $parts_arr;

            return $this->make_success(['data'=>$user_post]);
        }else{
            return $this->make_error('帖子不存在');
        }

    }

    public function post_publish(){

        header("Access-Control-Allow-Credentials: true");
        header("Access-Control-Allow-Origin: *");
        //CORS
        header("Access-Control-Request-Methods:GET, POST, PUT, DELETE, OPTIONS");
        header('Access-Control-Allow-Headers:x-requested-with,content-type,test-token,test-sessid');//注意头部自定义参数不要用下划线

        $id = isset($_POST['id']) ? $_POST['id'] : 0;//user_post表ID字段
        $type = isset($_POST['type']) ? $_POST['type'] : 0;//'内容类型ID（1我要晒机2配置清单3闲聊灌水）',
        $cover = isset($_POST['cover']) ? $_POST['cover'] : '';//封面
        $title = isset($_POST['title']) ? $_POST['title'] : '';//标题
        $content = isset($_POST['content']) ? $_POST['content'] : '';//正文
        $photos = isset($_POST['photos']) ? $_POST['photos'] : '';//照片
        $parts = isset($_POST['parts']) ? $_POST['parts'] : '';//配件


        global $wpdb;

        if(!$type || !$id){
            return $this->make_error("type或者id不能是0");
        }


        //根据不同类项目 投稿到指定板块下
        $category_id = 1;
        if($type == 1){//我要晒机
            $category_id = 56;
        }
        if($type == 2){//配置清单
            $category_id = 3;
        }

        //先保存文章
        $post = [];
        $post['post_author'] = 1;
        $post['post_date'] = date("Y-m-d H:i:s",time());
        $post['post_date_gmt'] = date("Y-m-d H:i:s",time());
        $post['post_content'] = $content;
        $post['post_title'] = $title;
        $post['post_name'] = $title;
        $post['post_category'] = [$category_id];

        $post_id = wp_insert_post($post);

        //给文章加缩略图
        //check file type
        $filetype = wp_check_filetype($cover, null);
        //set attachment data
        $attachment = [
            'post_mime_type' => $filetype['type'],
            'post_title' => $title,//sanitize_file_name(basename($img)),
            'post_excerpt' => $title,
            'post_content' => $title,
            'post_status' => 'inherit',
        ];
        //create attachment
        $attachment_id = wp_insert_attachment($attachment, $cover, $post_id);
        //include image.php
        require_once ABSPATH . "wp-admin/includes/image.php";
        //define attachment metadata
        $attachment_data = wp_generate_attachment_metadata($attachment_id, $cover);
        //assign metadata to attachment
        wp_update_attachment_metadata($attachment_id, $attachment_data);
        //and finally assign featured image to post
        set_post_thumbnail($post_id,$attachment_id);

        // 新增spider_fpv(特地要说明：虽然公用一张表，但是内容不是爬虫源头，而是用户自建)
        $wpdb->insert("spider_fpv",[
            'url' => '用户自建',
            'spider_id' => 5000000+$post_id,//伪造ID，默认500万开始
            'content' => $content,
            'photos' => $photos,//重要，这个是最核心的，公用的
            'parts' => $parts,
            'wp_posts_id' => $post_id,//重要，关联文章，也在用
            'create_time' => date("Y-m-d H:i:s",time()),
            'update_time' => date("Y-m-d H:i:s",time())
        ]);

        //处理照片
        $insert_photos = explode(',', $photos);
        $addition_content = '';
        foreach ($insert_photos as $ip){
            //拷贝一份图片 tiny.jpg
//            copy(ABSPATH.$ip,ABSPATH . $ip . tinyjpg());//无需拷贝tinypng
            //把图片上传到cos
            upload_img_to_cos(ABSPATH . $ip, $ip);
//            upload_img_to_cos(ABSPATH . $ip, $ip.tinyjpg());

            //把内容添加到文章末尾
            $addition_content .= '<img style="margin-top:10px;" class="size-full aligncenter" src="'.get_cos_domain().$ip.'" alt="'.$title.'" title="'.$title.'" />';
        }


        if($type == 1){//我要晒机
            //把photos 晒机内容添加到文章末尾
            wp_update_post([
                    'ID'           => $post_id,
                    'post_content' => $content . $addition_content
            ]);
        }
        if($type == 2){//配置清单
            //parts信息关联
            $parts = explode(',',$parts);
            foreach ( $parts as $partId){
                $wpdb->insert('fpv_parts',[
                    'fpv_id' => $post_id,//文章ID
                    'parts_id' => $partId,
                    'create_time' => date("Y-m-d H:i:s",time()),
                    'update_time' => date("Y-m-d H:i:s",time())
                ]);
            }
        }


        //最后把最新内容更新到user_post表
        $wpdb->update("user_post",[
            'content' => $content,
            'photos' => $photos,
            'parts' => $parts,
            'status' => 1,//审核通过
            'wp_posts_id' => $post_id,//重要，关联文章，也在用
            'title' => $title,
        ],['id'=>$id]);

        return $this->make_success("发表成功");

    }
	
}
